<template>
    <div class="home-tools">
        <el-popover placement="bottom" width="320" trigger="click" @hide="popoverHide">
            <div class="table-type">{{newTableRow.length === 0?'0 x 0':`${newTableRow[0]} x ${newTableRow[1]}`}} 表格</div>
            <table height="280" width="320" cellspacing="0" cellpadding="0" class="make-table">
                <tr class="table-row" v-for="rowItem in 12" :key="rowItem+'1'">
                    <td :class="['table-item',{'table-item-active':tableActive([rowItem,cloumItem])}]" v-for="cloumItem in 12" :key="rowItem+'-'+cloumItem" :data-index="rowItem+'-'+cloumItem"
                        @mouseenter="tableMouseEnter" @click="makeTable"></td>
                </tr>
            </table>
            <div slot="reference">
                <div class="img-btn flex-center">
                    <img src="../../../assets/img/create-table.png" alt="">
                </div>
                <div class="text-btn">新建表格</div>
            </div>
        </el-popover>
        <el-popover placement="bottom" width="400" trigger="click">
            <div class="flex-around">
                <div @click="createNewCharts('histogram')">
                    <div class="new-charts">
                        <img src="../../../assets/img/new-hist.png" alt="">
                    </div>
                    <div class="new-title">柱状图</div>
                </div>
                <div @click="createNewCharts('line')">
                    <div class="new-charts">
                        <img src="../../../assets/img/new-line.png" alt="">
                    </div>
                    <div class="new-title">折线图</div>
                </div>
                <div @click="createNewCharts('pie')">
                    <div class="new-charts">
                        <img src="../../../assets/img/new-pie.png" alt="">
                    </div>
                    <div class="new-title">饼图</div>
                </div>
                <div @click="createNewCharts('relation')">
                    <div class="new-charts">
                        <img src="../../../assets/img/new-relation.png" alt="">
                    </div>
                    <div class="new-title">气泡图</div>
                </div>
            </div>
            <div slot="reference">
                <div class="img-btn flex-center">
                    <img src="../../../assets/img/history-charts.png" alt="">
                </div>
                <div class="text-btn">新建统计图</div>
            </div>
        </el-popover>
        <el-popover placement="bottom" width="750" trigger="click" @show="popoverShow">
            <div>
                <el-table ref="singleTable" :data="fileList" highlight-current-row style="width: 100%" :max-height="maxHeight" @selection-change="handleSelectionChange">
                    <el-table-column type="selection">
                    </el-table-column>
                    <el-table-column type="index" label="序号" width="100">
                    </el-table-column>
                    <el-table-column property="fileName" label="文件名">
                    </el-table-column>
                    <el-table-column property="fileType" width="100" label="类型">
                    </el-table-column>
                    <el-table-column property="creatDate" label="创建时间">
                    </el-table-column>
                    <el-table-column label="操作" width="120">
                        <template slot-scope="scope">
                            <el-button type="text" @click="deleteFile(scope.row)">删除</el-button>
                            <el-button type="text" @click="openFile(scope.row)">查看</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="delete-file">
                    <el-button type="primary" size="small" @click="deleteFile">删除</el-button>
                </div>
            </div>
            <div slot="reference">
                <div class="img-btn flex-center">
                    <img src="../../../assets/img/create-charts.png" alt="">
                </div>
                <div class="text-btn">历史图表</div>
            </div>
        </el-popover>
    </div>
</template>

<script>
import moment from 'moment'
export default {
    inject: ['title'],
    data () {
        return {
            newTableRow: [],
            fileList: [],
            maxHeight: window.innerHeight / 4
        }
    },
    created () {
        this.title.name = '统计图表'
    },
    methods: {
        makeTable () {
            const [row, column] = this.newTableRow.length > 0 ? this.newTableRow : e.target.dataset.index.split('-')
            this.$router.push({ name: 'Table', params: { row: row, column: column } })
        },
        tableMouseEnter (e) {
            if (e.target.dataset.index) {
                this.newTableRow = e.target.dataset.index.split('-')
            }
        },
        tableActive (data) {
            if (this.newTableRow.length === 0) return false
            // if( data[0] && data[0] < this.newTableRow[0] && data[1]) return true
            return data[0] && data[0] <= this.newTableRow[0] && data[1] && data[1] <= this.newTableRow[1]
        },
        popoverHide () {
            this.newTableRow = []
        },
        createNewCharts (type) {
            const nameMap = {
                histogram: "柱状图",
                line: '折线图',
                pie: '饼图'
            }
            const rowData = [{ "rowKey": "类别1", "value": [40, 30, 38] }, { "rowKey": "类别2", "value": [20, 18, 32] }, { "rowKey": "类别3", "value": [40, 16, 8] }]
            const tableColumn = [{ "key": "" }, { "key": "系列1" }, { "key": "系列2" }, { "key": "系列3" }]
            const tableData = [{ "rowKey": "类别1" }, { "rowKey": "类别2" }, { "rowKey": "类别3" }]
            this.$router.push({
                name: 'ChartsInstance', params: {
                    rowData: rowData,
                    tableColumn: tableColumn,
                    tableData: tableData,
                    type: type,
                    // tableName: nameMap[type]
                    tableName: ''
                }
            })
        },
        async popoverShow () {
            const nameMap = {
                h: "柱状图",
                l: '折线图',
                p: '饼图',
                t: '表格',
                r: '气泡图'
            }
            const fs = require('fs')
            const path = require('path')
            let dirPath = path.join(window.$DATADIR, 'resc', 'user', 'charts')
            let fileList = await fs.promises.readdir(dirPath)
            if (Array.isArray(fileList)) {
                this.fileList = []
                fileList.forEach(fileItem => {
                    if (!fileItem.includes('.json')) return
                    const fileMessgae = fileItem.replace('.json', '').split('_b_s_c_')
                    const suffix = fileMessgae[1] || ''
                    const type = suffix.substr(-1, 1)
                    const time = suffix.substr(0, suffix.length - 1)
                    if (fileMessgae[0] && !isNaN(Date.parse(new Date(time)))) return
                    let obj = { fileName: '', creatDate: '', originPath: '', fileType: '' }
                    obj.fileName = fileMessgae[0]
                    obj.creatDate = moment(parseInt(time)).format('YYYY-MM-DD HH:mm:ss')
                    obj.fileType = nameMap[type]
                    obj.originPath = path.join(dirPath, fileItem)
                    this.fileList.push(obj)
                })
                this.fileList.sort((itemA, itemB) => new Date(itemB.creatDate).getTime() - new Date(itemA.creatDate).getTime())
            }
        },
        handleCurrentChange (val) {
            this.currentRow = val
            if (this.currentRow.originPath) {
                this._filePath = path.join(window.$DATADIR, 'resc', 'user', 'mindMap', this.currentRow.originPath)
            } else {
                this._filePath = path.join(window.$DATADIR, 'resc', 'MindMap', this.currentRow.systemPath)
            }
        },
        openFile (row) {
            if (row.fileType === '表格') {
                this.$router.push({ name: 'Table', params: { originPath: row.originPath } })
            } else {
                this.$router.push({ name: 'ChartsInstance', params: { originPath: row.originPath } })
            }
        },
        deleteFile (row) {
            const fs = require('fs')
            if (Array.isArray(this._fileList)) {
                this._fileList.forEach(item => {
                    if (item.originPath) {
                        fs.unlink(item.originPath, (err) => {
                            if (err) {
                                console.log(err)
                                this.$message.error('删除失败')
                                return
                            }
                            this.popoverShow()
                            this.$message.success('删除成功')
                        })
                    }
                })
                this._fileList = null
            } else {
                if (row.originPath) {
                    fs.unlink(row.originPath, (err) => {
                        if (err) {
                            console.log(err)
                            this.$message.error('删除失败')
                            return
                        }
                        this.popoverShow()
                        this.$message.success('删除成功')
                    })
                }
            }
        },
        handleSelectionChange (val) {
            this._fileList = val
        }
    }
}
</script>

<style lang="scss" scope>
.delete-file {
    text-align: center;
    color: #66b1ff;
    margin-top: 8px;
}
.home-tools {
    width: 100%;
    display: flex;
    justify-content: center;
    height: 100%;
    & > :nth-child(2) {
        margin: 0 180px;
    }
    .text-btn {
        width: 100%;
        text-align: center;
        color: #030313;
        font-size: 22px;
        margin-top: 25px;
    }
    .img-btn {
        width: 14vw;
        height: 14vw;
        max-width: 200px;
        max-height: 200px;
        background: #ffffff;
        box-shadow: 0px 1px 60px 0px rgba(184, 203, 215, 0.35);
        border-radius: 50%;
        img {
            width: 8.3vw;
            height: 8.3vw;
            max-width: 120px;
            max-height: 120px;
            position: relative;
            top: 8px;
            left: 12px;
        }
    }
}
.new-charts {
    width: 5.6vw;
    height: 5.6vw;
    max-width: 80px;
    max-height: 80px;
    background: rgba(#46b9f9, 0.1);
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    img {
        width: 2.8vw;
        height: 2.8vw;
        max-width: 40px;
        max-height: 40px;
        cursor: pointer;
    }
}
.new-title {
    font-size: 18px;
    font-weight: 400;
    color: #303133;
    text-align: center;
    margin-top: 15px;
    cursor: pointer;
}
</style>